<template>
  <el-container>
    <el-header height="40">
      <div class="p-a-mini flex-between">
        <BKSelect
          v-model="level"
          :mock="mock"
          size="small"
          :clearable="false"
          @change="levelChange"
        />
        <el-button
          size="small"
          type="primary"
          @click="updateMenu"
          v-if="!isModal"
          v-auth="'system:auth:aduit'"
        >
          权限审核规则
        </el-button>
        <div v-else />
      </div>
      <div
        class="config-tree-search flex-0 p-h-mini"
      >
        <el-input
          size="small"
          prefix-icon="el-icon-search"
          placeholder="输入关键字进行过滤"
          v-model="keyword"
          clearable
          class="m-b-mini"
        />
      </div>
    </el-header>
    <el-main>
      <BKTree
        ref="authTree"
        multiple
        :render-content="renderContent"
        :mock="treeData"
        class="flex-1 m-l-mini p-v-mini overflow-auto bk-tree-wrapper"
        has-line
        :default-expanded-keys="defaultExpandedKeys"
        node-key="id"
        @node-click="handleNodeClick"
        :filter-node-method="filterNode"
      />
    </el-main>
    <el-footer
      height="40"
      v-if="isModal"
    >
      <div
        class="d-flex ai-c jc-c p-v-mini"
        style="border-top: 1px solid #eee;"
      >
        <el-button
          @click="confirm"
          type="primary"
          size="small"
        >
          确定
        </el-button>
      </div>
    </el-footer>
    <BKModal
      v-model="visible"
      title="权限审核规则"
      width="400"
      height="800"
    >
      <MenuTree
        is-modal
        @refresh="refresh"
      />
    </BKModal>
  </el-container>
</template>

<script>
const iconMap = {
  F: 'el-icon-open',
  C: 'el-icon-menu',
  M: 'el-icon-folder'
}
export default {
  name: 'MenuTree',
  data () {
    return {
      level: 'A',
      treeData: [],
      visible: false,
      mock: [],
      defaultExpandedKeys: [],
      keyword: ''
    }
  },
  props: {
    isModal: {
      type: Boolean,
      default: false
    }
  },
  mounted () {
    this.init()
  },
  watch: {
    keyword (val) {
      this.$refs.authTree.filter(val)
    }
  },
  methods: {
    async init () {
      await this.getLevelList()
      this.levelChange()
    },
    levelChange () {
      this.getCheckedData()
      this.getTreeData()
    },
    async getLevelList () {
      const data = await this.$request.get('/ysjc/user/initAuthLevelList')
      this.mock = Object.keys(data).map(key => ({ label: data[key], value: key }))
      this.level = this.mock[0].value
    },
    updateMenu () {
      this.visible = true
    },
    renderContent (h, { node, data, store }) {
      return (
        <div class="custom-tree-node d-flex ai-c">
          {
            <span class="node-icon f-14">
              {
                <i class={'icon m-r-tiny ' + iconMap[data.att2]}/>
              }
              <span>{ node.label }</span>
            </span>
          }
        </div>
      )
    },
    setMenuData (data) {
      const flattenedMenus = []
      this.$utils.flattenList(data, flattenedMenus)
      this.flattenedMenus = flattenedMenus
      this.setCheckedMenus()
    },
    setCheckedMenus () {
      if (!this.roleMenus || !this.flattenedMenus) return
      const checkedMenuIds = []
      for (const rm of this.roleMenus) {
        const target = this.flattenedMenus.find(m => m.id === rm.MENU_ID.toString())
        if (target && target.isLeaf) {
          checkedMenuIds.push(target.id)
        }
      }
      this.$refs.authTree.setCheckedKeys(checkedMenuIds)
    },
    async getCheckedData () {
      const { rows } = await this.$request.post('/SingleTable/curd', {
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_PW_MENU_EXAMINE',
        methodCode: 'select',
        methodParams: JSON.stringify({
          queryParam: {
            APPROVAL_LEVEL: this.level
          }
        })
      })
      this.roleMenus = rows
      this.setCheckedMenus()
    },
    async getTreeData () {
      const data = await this.$request.post('/tree/data', {
        appId: 'YSJC',
        bzCode: 'YSJC',
        node: 'ROOT',
        queryParams: { bzCode: 'YSJC', APPROVAL_LEVEL: this.level },
        treeConfigId: this.isModal ? 'YSJC_QXGL_JSGL' : 'YSJC_QXSH_MENU_TREE'
      })
      const flat = []
      this.$utils.flattenList(data, flat)
      this.defaultExpandedKeys = flat.filter(item => item.att2 === 'M').map(item => item.id)
      this.treeData = this.recurseTreeData(data)
      this.setMenuData(data)
    },
    recurseTreeData (data) {
      return data.map(item => {
        return {
          disabled: !this.isModal,
          ...item,
          children: item.children && item.children.length ? this.recurseTreeData(item.children) : null
        }
      })
    },
    confirm () {
      this.$confirm('请确认是否保存数据', '提示', { type: 'warning' }).then(async () => {
        const nodes = this.$refs.authTree.getCheckedNodes()
        const halfNodes = this.$refs.authTree.getHalfCheckedNodes()
        // await this.$request.post('/SingleTable/curd', {
        //   appId: 'YSJC',
        //   bzCode: 'YSJC',
        //   metaSet: 'YSQJC_PW_MENU_EXAMINE',
        //   methodCode: 'override',
        //   methodParams: JSON.stringify({
        //     deleteParam: {
        //       APPROVAL_LEVEL: this.level
        //     },
        //     batchParam: nodes.concat(halfNodes).map(r => {
        //       return {
        //         APPROVAL_LEVEL: this.level,
        //         MENU_ID: r.id
        //       }
        //     })
        //   })
        // })
        await this.$request.post('/ysjc/user/updateUserMenu', {
          MENU_ID: nodes.concat(halfNodes).map(r => r.id).join(','),
          EXAMINE_TYPE: '0',
          APPROVAL_LEVEL: this.level
        })
        this.$message.success('操作成功！')
        this.$emit('refresh')
      })
    },
    refresh () {
      this.levelChange()
      this.visible = false
    },
    handleNodeClick (data) {
      this.$emit('node-click', { data, level: this.level })
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1
    }
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #0151dc !important;
    border-color: #0151dc !important;
  }

  ::v-deep .el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner {
    background-color: #0151dc !important;
    border-color: #0151dc !important;
  }

  ::v-deep .bk-tree-wrapper .is-current > .el-tree-node__content > .custom-tree-node {
    color: #fff;
    background: #f2ba13;
    border-radius: 3px;
    padding: 2px 4px;
  }
</style>
